package cn.buaa.edu.cn.ffmpegservice.service.impl;

import cn.buaa.edu.cn.ffmpegservice.config.SystemUtil;
import cn.buaa.edu.cn.ffmpegservice.domain.dto.Record;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@RequiredArgsConstructor
public class AsyncService {

    private final Record record;

    @Getter
    private static Map<String, Process> processMap = new ConcurrentHashMap<>();
    @Getter
    public Process process;

    private String info;

    private String getCommand(String instanceID) {
        String command = "";
        if (SystemUtil.isLinux()) {
            //linux下
            //ffmpeg -f video4linux2 -i /dev/video0  -f flv rtmp://192.168.103.142:1937/live/12
//ffmpeg -f video4linux2 -s 1920x1080 -r 30 -vcodec mjpeg -i /dev/video0 -pix_fmt yuv420p -b:v 2000k -vcodec libx264 -preset veryfast -f flv rtmp://192.168.6.21:32322/live/edgetest
            command = "ffmpeg -f video4linux2 " +
                    " -s 1920x1080 -r 30 -vcodec mjpeg " +
                    " -i " +record.getCameraName() +
                    " -pix_fmt yuv420p -b:v 2000k -vcodec libx264 -preset veryfast " +
                    " -f flv " + record.getRtmpAddress() + "/" + instanceID;
        } else if (SystemUtil.isWindows()) {
            //windows下
            //ffmpeg  -f dshow -i video="HP Wide Vision HD Camera"  -c:v libx264 -c:a aac -f flv rtmp://192.168.103.142:1936/live/test
            command = "ffmpeg  -f dshow " +
                    " -i video=\"" + record.getCameraName() + "\"  " +
                    " -c:v libx264 -c:a aac " +
                    " -f flv " + record.getRtmpAddress() + "/" + instanceID;
        }
        System.out.println("ffmpeg推流命令：" + command);
        return command;
    }

    @Async
    public void doTask(String instanceID) throws IOException {
        //记录开始时间
        long start = System.currentTimeMillis();
        StringBuilder stringBuilder = new StringBuilder();
        String command = getCommand(instanceID);
        process = Runtime.getRuntime().exec(command);
        processMap.put(instanceID, process);
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String str = reader.readLine();
        while (null != str) {
            if(str.contains("Error") || str.contains("Could not")){
                stringBuilder.append(str).append('\n');
            }
            System.out.println("视频推流信息[" + str + "]");
            str = reader.readLine();
            if (null == process) {
                break;
            }
        }
        process = null;
        //记录结束时间
        long end = System.currentTimeMillis();
        String time = "完成任务耗时：" + (end - start) / 1000 + "秒";
        System.out.println(time);
        info = time;
        stringBuilder.append(time).append('\n');
//        return stringBuilder;
    }

    public String endTask() throws IOException {
        try {
            process.getOutputStream().write("q".getBytes());
            process.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        process = null;
        return info;
    }
}
